package com.sh.exceptions;

import com.sh.common.BaseResult;
import com.sh.common.enums.BizCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult validException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        StringBuffer buffer = new StringBuffer();

        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                buffer.append(error.getDefaultMessage());
                buffer.append(";");
            });
        }
        return BaseResult.fail(BizCodeEnum.PARAM_VALID_ERROR.getCode(), buffer.toString());
    }

    @ExceptionHandler(value = BizException.class)
    public BaseResult bizException(BizException exception) {
        return BaseResult.fail(exception.getCode(), exception.getMessage());
    }


}
